﻿using FlexFlow.Base.Interface;
using FlexFlow.Model;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlexFlow.DataProvider.MongoDB
{
    /// <summary>
    /// 表示基于MongoDb的流程实例管理器
    /// </summary>
    public class MongoDbProcessInstanceProvider : MongoDBPhysicalModelProvider<ProcessInstance>,IProcessInstanceProvider
    {
        public override ProcessInstance Create()
        {
            return new ProcessInstance()
            {
                State = ProcessInstanceState.Initiated,
                CreateTime = DateTime.Now
            };
        }
        /// <summary>
        /// 更新流程实例状态
        /// </summary>
        /// <param name="procInsId">
        /// 要更新状态的流程实例Id
        /// </param>
        /// <param name="state">
        /// 要更新的状态
        /// </param>
        /// <returns>
        /// 更新结果
        /// </returns>
        /// <remarks>
        /// 请级联更新LastFlowTime
        /// </remarks>
        public bool UpdateState(Guid procInsId, ProcessInstanceState state)
        {
            var updef = this.BuildUpdateDef(m => m.State, state);
            updef = this.BuildUpdateDef(m => m.LastFlowTime, DateTime.Now, updef);
            return this.Update(procInsId, updef);
        }

        /// <summary>
        /// 更新指定流程实例的当前活动
        /// </summary>
        /// <param name="procInsId">
        /// 流程实例Id
        /// </param>
        /// <param name="currentActId">
        /// 当前活动Id
        /// </param>
        /// <returns>
        /// 更新结果
        /// </returns>
        /// <remarks>
        /// 请级联更新LastFlowTime
        public bool UpdateCurrentActivity(Guid procInsId, Guid currentActId)
        {
            var updef = this.BuildUpdateDef(m => m.CurrentActivityId, currentActId);
            updef = this.BuildUpdateDef(m => m.LastFlowTime, DateTime.Now, updef);
            return this.Update(procInsId, updef);
        }

        /// <summary>
        /// 根据用户ID取得流程实例列表
        /// </summary>
        /// <param name="userId">
        /// 用户ID
        /// </param>
        /// <returns>
        /// 流程实例列表
        /// </returns>
        public List<ProcessInstance> GetByUID(Guid userId)
        {
            FilterDefinition<ProcessInstance> filter = (FilterDefinition<ProcessInstance>)(m => m.Creator == userId);
            return GetCollection().GetAll(filter);
        }
    }
}
